<template>
	<!-- 关联手机 -->
	<view>
		<j-load v-if="loading"></j-load>
		<view v-else>
			<!-- 电话列表 -->
			<view class="cu-list menu card-menu margin-top" v-for="(item,i) in list" :key="i">
				<view class="cu-item bg-white" style="padding-top:30upx;padding-bottom: 30upx;">
					<view class="content">
						<view class="cu-form-group" style="padding:0">
							<image src="https://statics.xmcsrv.net/weixin/cloud/action/setPhones_.svg" mode="aspectFit"
								style="width:60upx;height:52upx;"></image>
							<input type="text" :placeholder="$t('JLink.placeholder.default')" :disabled="true" :value="item.value"
								class="margin-left" @blur="inputChange($event,i)" />
						</view>
						<view class="text-red text-sm" style="padding:0 60upx">
							<!-- 输入的手机格式有误 -->
							<view v-show="item.err">{{$t('JLink.placeholder.phoneFormat')}}</view>
							<!-- 重复手机号 -->
							<view v-show="!item.err&&item.repeat">{{$t('JLink.placeholder.phoneRepeat')}}</view>
						</view>
					</view>
					<!-- 操作 -->
					<view class="action">
						<text
							class="text-gray text-lg margin-right-sm text-black">{{i==0 ? $t('JLink.publicText.main'): $t('JLink.publicText.spare')}}</text>
						<!-- 删除 -->
						<text class="cuIcon-close text-gray" style="font-size:36upx" @tap="delClick(i)"></text>
					</view>
				</view>
			</view>
			<!-- 添加 -->
			<view v-if="isAdd&&list.length<2" class="text-center">
				<button class="cu-btn round line-cyan margin-tb" style="background-color: #fff;" @tap="addClick">
					<uni-icons type="plusempty" size="20" color="#1cbbb4"></uni-icons>
					{{$t('JLink.publicText.add')}}
				</button>
			</view>
		</view>
		<error-modal ref="errModal" :modalName="modalName" :errCode="errCode" @changeModalName="hideModal"></error-modal>
		<j-modal :value="mobilePopup" :showCancel="true" title="请输入手机号" @ok="dialogInputConfirm2()" @cancel="mobilePopup=false">
			<view slot="content">
				<uni-easyinput class="uni-mt-5" trim="all" :maxlength="11" type="number" v-model="mobile" placeholder="请输入手机号" ></uni-easyinput>
			</view>
		</j-modal>
	</view>
</template>
<script>
	let that = null
	const {debounce} = require('@/utils/util.js')
	import errorModal from "../components/modal/error"
	import {
		getDeviceToken,
		VoLTE_PhoneList,
		VoLTE_SetPhone
	} from "@/API/api.js"
	import {
		getGlobalProperties
	} from '@/utils/globalProperties.js'
	const {
		getDeviceInfo,
		cardQR,
		getDeviceBySn
	} = getGlobalProperties()
	export default {
		components: {
			errorModal
		},
		data() {
			return {
				loading: false,
				list: [], //手机号列表
				token: '', //设备令牌
				urlParams: {
					type: '',
					sn: ''
				},
				errorList: [], //手机号格式输入错误提示
				modalName: '',
				phones: [],
				errCode: '',
				isAdd: false, //是否显示添加按钮
				deviceAccount: { //设备账号
					username: '',
					password: ''
				},
				sn:'',
				loginToken:'',
				mobile:'',
				mobilePopup:false
			}
		},
		onLoad(e) {
			console.log('lllllll==',e, getGlobalProperties());
			const { sn, type, devName, u,p,adminToken,userGroupId } = e;
			this.sn = sn
			this.urlParams = {
				sn,
				type,
				devName
			}
			let username = u=='null'||'undefined'?'':u
			let password = p=='null'||'undefined'?'':u
			this.deviceAccount = {
				username: username,
				password: password,
				loginToken: adminToken,
				encryptType:''
			};
			console.log('获取参数===',u,p,this.deviceAccount);
			that = this
			this.getAdminToken(sn)
			// this.getDeviceInfoByPage(sn,userGroupId)
			// this.deviceBySn({devId:sn,encryptType:'AES'},(res)=>{
			// 	const {u,p,adminToken,encryptType} = res;
			// 	this.deviceAccount = {
			// 		username:u,
			// 		password:p,
			// 		loginToken:adminToken,
			// 		encryptType
			// 	};
			// })
		},
		onShow() {
			const {
				sn,
				type
			} = this.urlParams;
			this.getPhoneList(sn,type)
		},
		methods: {
			
			//获取关联手机号列表
			getPhoneList(sn,type){
				this.loading = true; //加载
				this.isAdd = false;
				this.list = [];
				this.phones = [];
				this.handleDeviceToken(sn, type, (res) => {
					this.loading = false; //取消加载
					this.isAdd = true; //显示添加按钮
					const {
						phones,
						token
					} = res;
					this.token = token;
					// 手机列表重组
					if (phones && phones.length) {
						this.phones = phones;
						phones.forEach(t => {
							this.list.push({
								value: t,
								err: false,
								repeat: false
							})
						})
						console.log('list====',this.list,phones);
					}
					this.$logs({info:'获取关联手机号getPhoneList', sn:sn,result:res,phones:phones,list:this.list})
				}, (code) => {
					this.loading = false; //取消加载
					this.isAdd = false; //隐藏添加按钮
					if (code) {
						this.modalName = 'errorMessage';
						this.errCode = `v-${code}`;
					}
				})
				this.handleBack();
			},
			// 获取设备最新的adminToken
			getAdminToken(sn){
				let data = {
					deviceNo:sn,
					isLatest:true
				}
				getApp().globalData.api.getDeviceTokenLocal(data, (result) => {
					this.loginToken = result.adminToken
					this.deviceAccount.loginToken = result.adminToken
				});
			},
			//获取设备信息
			getDeviceInfoByPage(sn,userGroupId) {
				const data = {
					deviceNo: sn,
					userGroupId: userGroupId,
					page: 1,
					limit: 999,
				};
				getApp().globalData.api.getDeviceListByPage(data, (result) => {
					// console.log('某个房间的设备列表:', result);
					// this.deviceList = result.data || []
					// this.deviceList.forEach((item) => {
					// 	if (item.deviceNo.includes('vir')) {
					// 		this.$set(item, 'isVirtual', true)
					// 	}
					// })
					// this.getDeviceListInfo();
				});
			},
			// 获取设备信息(用户名和密码 / token)
			deviceBySn(message, callback) {
				try {
					// let data =getDeviceInfo(message);// 获取设备信息（新的）
					// if(cardQR==='ios'){
					// 	window.getDeviceInfoResponse = function(res){
					// 		data = res ? JSON.parse(res) : {};
					// 		callback(data)
					// 	}
			  // }else{
					// 	data = JSON.parse(data);
					// 	callback(data)
					// }
				} catch (err) {
					//在此处理错误
					const {
						devId
					} = message;
					// let data = getDeviceBySn(devId);// 获取设备信息（老的的）
					// if(cardQR==='ios'){
					// 	window.getDeviceBySnResponse = function(res){
					// 		data = res ? JSON.parse(res) : {};
					// 		callback(data)
					// 	}
					// }else{
					// 	data = JSON.parse(data);
					// 	callback(data)
					// }
				}
			},
			// 获取设备token以及关联手机列表
			handleDeviceToken(deviceId, type, callback, callfinally) {
				getDeviceToken({
					deviceId
				}).then(res => {
					let token = res.token;
					VoLTE_PhoneList(type, token).then(mes => {
						const {
							code,
							data
						} = mes;
						if (code === 2000) {
							const {
								alarmTypes
							} = data;
							// this.phoneInfo = data;
							data.token = token;
							if (alarmTypes) {
								let alarmTypes_keys = Object.keys(alarmTypes);
								ALARMTYPE.value.forEach(j => {
									alarmTypes_keys.forEach(z => {
										// 对应已选择哪些报警类型
										if (j.value === z) {
											j.check = alarmTypes[z];
										}
									})
								})
							}
							callback(data)
						} else {
							callfinally(code)
						}
						console.log('获取云电话获取关联手机号VoLTE_PhoneList',mes);
						this.$logs({ info: '获取云电话获取关联手机号VoLTE_PhoneList', data:deviceId,result:mes})
					}).catch(() => {
						callfinally()
					})
				}).catch(() => {
					callfinally()
				})
			},
			handleBack() {},
			// 设置关联手机号
			setPhone(callback) {
				const sn = this.sn
				const userId = uni.getStorageSync('userInfo').userId
				const {
					type,
					devName
				} = this.urlParams;
				const {
					token,
					phones
				} = this;
				const {
					username,
					password,
					loginToken,
					encryptType
				} = this.deviceAccount;
				let params = type === 'voes' ? {
					phones,
					devName,
					username,
					password,
					loginToken,
					// sn,
					// userId
					// encryptType
				} : {
					phones,
					devName
				}; //api参数
				VoLTE_SetPhone(type, token, params).then(res => {
					const {
						code,
						msg
					} = res;
					if (code === 2000) {
						uni.showToast({
							title: this.$t('JLink.publicText.setSuccess'), //设置成功
						});
						callback()
					} else {
						this.modalName = 'errorMessage';
						this.errCode = `v-${code}`;
					}
					console.log('设置云电话====',params,res);
					this.$logs({ info: '设置云电话关联手机号VoLTE_SetPhone',data:params,result:res})
				}).catch(() => {}).finally(() => {uni.hideLoading()})
			},
			// input事件
			inputChange(e, i) {
				let val = e.detail.value;
				this.list[i].value = val;
				// 重复初始化false
				this.list.forEach(z => {
					z.repeat = false;
				})
				if (!this.phoneAuth(val)) {
					this.list[i].err = true;
				} else {
					this.list[i].err = false;
					// 查询重复
					for (var a = 0; a < this.list.length; a++) {
						for (var b = a + 1; b < this.list.length; b++) {
							if (this.list[a].value == this.list[b].value) {
								this.list[b].repeat = true
							}
						}
					}
					// 去除空数据
					let isRepeat = false;
					let that = this
					this.phones = this.list.filter(function(t) {
						if (t.repeat) {
							isRepeat = true
						}
						return t.value && t.value.trim() && that.phoneAuth(t.value) && !t.repeat;
					}).map(t => {
						return t.value
					})
					// 设置关联手机号
					if (!isRepeat) {
						this.setPhone(() => {})
					}

				}
			},
			// 添加
			addClick() {
				// this.list.push({
				// 	value: '',
				// 	err: false,
				// 	repeat: false
				// })
				this.mobile = ''
				this.mobilePopup = true
			},
			dialogInputConfirm:debounce(()=>{
				that.dialogInputConfirm2()
			}),
			//确认添加
			dialogInputConfirm2(){
				this.$logs({ info: '开始添加云电话', data: this.phones})
				if (!this.phoneAuth(this.mobile)) {
					uni.showToast({
						title:'请输入正确的手机号',
						icon:'none'
					})
					return
				} 
				// 查询重复
				for (var a = 0; a < this.list.length; a++) {
					if(this.list[a].value == this.mobile){
						uni.showToast({
							title:'该手机号已存在',
							icon:'none'
						})
						return
					}
				}
				this.phones.push(this.mobile)
                uni.showLoading({
                    title: '正在添加',
                    mask: true
                })
				this.mobilePopup = false
				console.log('手机号===',this.phones);
				// 设置关联手机号
				this.setPhone(() => {
					// this.mobilePopup = false
					const {
						sn,
						type
					} = this.urlParams;
					this.getPhoneList(sn,type)
				})
				this.$logs({ info: '添加云电话', data: this.phones})
			},
			// 删除
			delClick(index) {
				this.$logs({ info:'删除云电话', index:index,list:this.list})
				let value = this.list[index].value;
				if (this.phoneAuth(value)) {
					this.phones.splice(index, 1);
					this.setPhone(() => {
						this.list.splice(index, 1);
					})
				} else {
					this.list.splice(index, 1);
				}
			},
			phoneAuth(val) {
				let pattern = /^1[3456789]\d{9}$/;
				return pattern.test(val)
			},
			hideModal(code) {
                if(code === 'v-4005') {
                    uni.navigateBack()
                    return
                }
				this.modalName = ''
				const {
					sn,
					type
				} = this.urlParams;
				this.getPhoneList(sn,type)
			}
		}
	}
</script>

<style lang="less" scoped>
	@import '@/common/style/main.css';
</style>
